const express = require('express')
const router = express.Router()
const connection = require('../mysql')

// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')
const config = require('../../config')

// 生成 Token 字符串



//! 登录接口 
router.post('/login', (req, res) => {
    console.log(req.body.params);
    const {username, password} = req.body.params

    const sql = 'select * from users where username=?'
    connection.query(sql, [username],(err, result) => {
        if (err) return res.status(500).send('数据库错误')
        console.log(result);
        
        if (result.length === 0) {
            return res.send({
                status: 201,
                message: '用户不存在'
            })
        }else{
            const user = {...result[0], password: ''}
            const pwd = result[0].password
            
            if(password === pwd){

                const tokenStr = jwt.sign(user, config.jwtSecretKey, {
                    expiresIn: '10h', // token 有效期为 10 个小时
                  })

                return res.send({
                    status: 200,
                    message: '登录成功',
                    token: 'Bearer ' + tokenStr
                })
            }else{
                return res.send({
                    status: 404,
                    message: '密码错误'
                })
            }
        }

        
    })
})


//! 注册接口 
router.post('/register', (req, res) => {
    console.log(req.body.params);
    const {username, password} = req.body.params

    // 验证用户名是否存在
    const sql = 'select * from users where username=?'
    connection.query(sql, [username], (err, result) =>{
        if (err) return res.status(500).send('数据库错误')
        
        if (result.length > 0) {
            return res.send({
                status: 404,
                message: '用户名已存在'
            })
        }else{
            // 存入
            const sql = 'insert into users (username, password) values (?,?)'
            connection.query(sql, [username, password], (err, result) => {
                if (err) return res.status(500).send('数据库错误')
                return res.send({
                    status: 200,
                    message: '注册成功'
                })
            })
        }
    })
})







module.exports = router;